from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import mixins
from rest_framework import generics
from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters

from .models import Goods,GoodsCategory
from .serializer import GoodsSerializer,CategorySerializer
from .filters import GoodsFilter
# class GoodsView(APIView):
#     def get(self,request,format=None):
#         goods = Goods.objects.all()[:10]
#         goods_json = GoodsSerializer(goods,many=True)
#         # 通过serializer验证前端传递的参数
#         return Response(goods_json.data)
class GoodsPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'
    page_query_param = 'page'
    max_page_size = 100
#
class GoodsView(generics.ListAPIView):
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer
    pagination_class = GoodsPagination

class GoodsViewSet(mixins.ListModelMixin,viewsets.GenericViewSet):
    '''
        分页，搜索，排序，过滤
    '''
    serializer_class = GoodsSerializer
    pagination_class = GoodsPagination
    queryset = Goods.objects.all()
    filter_backends = (DjangoFilterBackend,filters.SearchFilter,filters.OrderingFilter)
    # filter_fields = ('category', 'name')
    # search_fields = ('category', 'name')
    filter_class = GoodsFilter
    search_fields = ('name','goods_brief','goods_desc')
    ordering_fields = ('shop_price','sold_num')


class CategoryViewset(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    list:
        商品分类列表数据
    retrieve:
        获取商品分类详情
    """
    queryset = GoodsCategory.objects.filter()
    serializer_class = CategorySerializer